/**
 * Alltosun - admin.js 后台通用JS代码
 * Copyright (c) 2009-2011 Alltosun.INC - http://www.alltosun.com
 * Date: 2011/01/06
 * @author gaojj@alltosun.com
 * @requires jQuery v1.4.4+
 * @requires jQuery-ui v1.8.7+
 */
// 删除提示信息 为了兼容原有后台程序移植过来的 将来将要被废除
var prompt = {
  'prompt': "确定要删除记录吗?",
  'nochange': "您没有要删除的记录",
  'errors': "删除失败"
};
var predefineParam;

var resType = resType || '';
var resName = resName || '';
res_name = '';
$(function(){
  
  // js_showLogBtn 展示某个资源的log，需要定义data-res_name data-res_id属性 liw add 2014-11-26
  $('.js_showLogBtn').click(function(){
    var thisBtn = $(this);
    var resName = thisBtn.data('res_name');
    var resId   = thisBtn.data('res_id');
    if(!resName || !resId) {
      alert("资源信息不正确，不能展示日志");
      return;
    }
    var id = 'log_'+resName+'_'+resId;
    var d = ace.dialog({
      content: '<div id="'+id+'" class="logmsg-box"><div style="padding:50px 0px;text-align:center;"><img src="'+siteUrl+'/images/loading-blue.gif"/></div></div>'
    });
    $.getJSON(siteUrl+'/log/admin/show', { res_name:resName, res_id:resId }, function(json){
      if(json.info !='ok') {
        alert(json.info);
      } else {
        var logList = json.log_list.join('') || "暂无日志记录";
        $('#'+id).html(logList);
      }
    }).error(function(){
      alert("网络错误");
    });
  });
  
  // added by ninghx 2012-07-31 将页面中的时间插件转移到公用的js中
  $('#startDate, #stopDate, .js-date-picker').datepicker({
    dateFormat: 'yy-mm-dd',
    showButtonPanel: true,
    yearRange: '1900:'+new Date().getFullYear(),
    changeYear:true,
    changeMonth:true,
    maxDate: new Date(),
    yearSuffix: ''
  });
  
  // 点击列表选中checkbox
  $(".dataBox table tbody  tr").click(function(e){
    var clickTarget = $(e.target);
    // 当直接点击checkbox时，不做checked的切换
    if (clickTarget.is("input.listSelect")) {
      return;
    }
    var listCheckbox = $("input.listSelect", $(this));
    if (listCheckbox.is(":disabled")) {
      return;
    }
    if (listCheckbox.attr("checked")) {
      listCheckbox.removeAttr("checked");
    } else {
      listCheckbox.attr("checked", "checked");
    }
  });
  
  // 用于去除mozilla中radio和checkbox的bug问题
  if($.browser.mozilla) $("form").attr("autocomplete", "off");

  // 全选
  $("input.selectAll").live('click', function(){
    if ($(this).attr("checked")) {
      $("input.selectAll, input.listSelect").not(":disabled").attr("checked", "checked");
    } else {
      $("input.selectAll, input.listSelect").not(":disabled").removeAttr("checked");
    }
  });
  
  // 审核
  $(".doVerify").click(function(e){
    e.preventDefault();
    e.stopPropagation();
    var selectId = $(this).closest("tr").attr("id").substring(8);
    if (!selectId) {
      alert('请选择要操作记录');
    }
    
    if (!confirm("确定要执行此操作吗？")) {
      return false;
    }
    
    var clickObj = $(this);
    var url = clickObj.attr("href");
    $.post(url, { 'id':selectId }, function(json){
      if (json.info != 'ok') {
        alert(json.info);
      } else {
        clickObj.closest("tr").fadeOut(function(){
          $(this).remove();
          interLineColor();
        });
      }
    }, 'json');
    return false;
  });
  
  // 状态更改（还原或转为草稿）
  $(".changeStatus").live('click', function(e){
    e.preventDefault();
    e.stopPropagation();
    var selectId = $(this).closest("tr").attr("id").substring(8);
    if (!selectId) {
      showMsg('请选择要操作记录');
    }
    
    var clickObj = $(this);
    var url = clickObj.attr("href");
    var lines = $(this).parent().attr('rowspan');
    showConfirm('确定要执行此操作吗？', 1, function(){
      $.post(url, { 'id':selectId }, function(json){
        if (json.info != 'ok') {
          alert(json.info);
        } else {
          clickObj.closest("tr").fadeOut(function(){
            if (lines) {
              for (var i = 1; i < lines; i++) {
                $(this).next().remove();
              }
            };
            $(this).remove();
            interLineColor();
          });
        }
      }, 'json');
    });
    return false;
  });

  // 状态更改--刷新页面而不是删除tr
  $(".changeStatus-fresh").live('click', function(e) {
      e.preventDefault();
      e.stopPropagation();
      var selectId = $(this).closest("tr").attr("data-id");
      if (!selectId) {
          showMsg('请选择要操作记录');
      }

      var clickObj = $(this);
      var url = clickObj.attr("href");
      var confirm = clickObj.attr("data-confirm");
      if (!confirm) {
          confirm = '确定要执行此操作吗？';
      }
      showConfirm(confirm, 1, function() {
          $.post(url, {'id' : selectId}, function(data) {
              if (data.flag == 1) {
                  showMsg(data.message);
              } else {
                  showMsg('操作成功');
                  setTimeout(function(){
                      window.location.reload();
                  }, 500);
              }
          }, 'json');
      });
      return false;
  });

//单个删除
  $(".deleteOneUser").live('click',function(e){
    e.preventDefault();
    e.stopPropagation();
    var selectId = $(this).closest("tr").attr("id").substring(8);
    var roleId = $(this).closest("tr").data("id");
    if (!selectId) {
      alert('请选择要操作记录');
    }
    
    var clickObj = $(this);
    var url = clickObj.attr("href");
    var cardListBox = clickObj.closest('.cardListBox');
    var lines = $(this).parent().attr('rowspan');
    showConfirm('确定要删除该用户吗？', 1, function(){
      $.post(url, {  'user_id':selectId }, function(json){
        if (json.info != 'ok') {
          alert(json.info);
        } else {
          clickObj.closest("tr").fadeOut(function(){
            if (lines) {
              for (var i = 1; i < lines; i++) {
                $(this).next().remove();
              }
            };
            $(this).remove();
            interLineColor();
            
            if (cardListBox) {
              var trNum = cardListBox.find('.deleteOneUser').length;
              var level_total = cardListBox.attr('data-level_total');
              consoleLog(trNum);
              consoleLog(level_total);
              if (trNum < level_total) {
                $('.addCard').show();
              }
            }
          });
        }
      }, 'json');
    });
    return false;
  });
  
  // 单个禁用
  $(".deleteOne").live('click',function(e){
    e.preventDefault();
    e.stopPropagation();
    var selectId = $(this).closest("tr").attr("id").substring(8);
    var roleId = $(this).closest("tr").data("id");
    if (!selectId) {
      alert('请选择要操作记录');
    }
    
    var clickObj = $(this);
    var url = clickObj.attr("href");
    var cardListBox = clickObj.closest('.cardListBox');
    var lines = $(this).parent().attr('rowspan');
    showConfirm('确定要禁用该条记录吗？', 1, function(){
      $.post(url, {  'user_id':selectId, 'role_id':roleId }, function(json){
        if (json.info != 'ok') {
          alert(json.info);
        } else {
          clickObj.closest("tr").fadeOut(function(){
            if (lines) {
              for (var i = 1; i < lines; i++) {
                $(this).next().remove();
              }
            };
            $(this).remove();
            interLineColor();
            
            if (cardListBox) {
              var trNum = cardListBox.find('.deleteOne').length;
              var level_total = cardListBox.attr('data-level_total');
              consoleLog(trNum);
              consoleLog(level_total);
              if (trNum < level_total) {
                $('.addCard').show();
              }
            }
          });
        }
      }, 'json');
    });
    return false;
  });

  // 批量禁用
  $(".deleteAll").live('click', function(e){
    e.preventDefault();
    var url = $(this).attr("href");
    var ids = getCheckedIds();
    deleteAll(url, ids);
    $("input[name=selectAll]").not(":disabled").removeAttr("checked");
    return false;
  });

  // 点击列表选中checkbox
  $("tbody > tr", $("#AnTable")).click(function(e){
    var clickTarget = $(e.target);
    // 当直接点击checkbox时，不做checked的切换
    if (clickTarget.is("input[name=listSelect]")) {
      return;
    }
    var listCheckbox = $("input[name=listSelect]", $(this));
    if (listCheckbox.is(":disabled")) {
      return;
    }
    if (listCheckbox.attr("checked")) {
      listCheckbox.removeAttr("checked");
    } else {
      listCheckbox.attr("checked", "checked");
    }
  });

  // 批量转移分类
  $('#moveCategory').click(function(){
    $.getJSON("admin/category/get_list&res_name="+resName, function(data){
      var input='&nbsp;&nbsp;&nbsp;';
      input += '<select name="move_category" id="moveCategorySelect">';
      input += '<option>请选择目标分类</option>';
      $.each(data, function(i,item){
        input += '<option value="'+item['id']+'">'+item['name']+'</option>';
      });
      input += '</select>';
      $('#moveCategory').after(input);
      $('#moveCategory').unbind();
      $("#moveCategorySelect").change(function(){
        var categoryId = $(this).val();
        moveCategory(categoryId);
        $(this).children("option:first").attr('selected', 'selected');
        return false;
      });
    });
  });
});

/**
 * 批量禁用
 * @param url
 * @return
 */
function deleteAll(url, ids){
  var idstr = ids.join(',');
  if (!idstr) {
    showMsg("请选择要禁用的记录");
    return false;
  }
  var postData = { 'id': idstr };
  showConfirm('确定要禁用这些记录吗？', 1, function(){
    $.post(url, postData, function(json){
      if (json.info != 'ok') {
        alert(json.info);
      } else {
        $.each(ids, function(k, v){
          $("#dataList"+v).fadeOut(function(){
            $(this).remove();
          });
        });
        interLineColor();
      }
    }, 'json');
  });
}

/**
 * 为了兼容原有后台程序移植过来的 将来将要被废除
 * 单个删除
 * @param url
 * @param id
 * @return
 */
function del_one(url,id){
  if(!confirm(prompt.prompt)) return false;
  var sendata = {id:id, 'res_name':res_name};
  if (typeof(predefineParam) != 'undefined') {
    $.extend(sendata, predefineParam);
  }
  $.getJSON(url, sendata,function(data){
    if(data.info == 'ok'){
      var text = 'list_'+id;
      if (typeof(predefineFun) == 'undefined') {
        $("#"+text).fadeOut();
      } else {
        $.extend({ybo:predefineFun});
        $.ybo(text);
      }
    }else{
      alert(data.info);
      return false;
    }
  });
}
/**
 * 为了兼容原有后台程序移植过来的 将来将要被废除
 * 批量删除
 * @param url
 * @return
 */
function del(url){
  if(!confirm(prompt.prompt)) return false;
  var ids = '';
  $(".select_s input:checked").each(function(){
    var id = $(this).closest("tr").attr("id").substring(5);
    ids += id+',' ;
  });
  if(!ids){
    alert(prompt.nochange);
    return false;
  }
  var sendata = {id:ids};
  if (typeof(predefineParam) != 'undefined') {
    $.extend(sendata, predefineParam);
  }
  $.getJSON(url, sendata, function(json){
    if (json.info == 'ok'){
        var $obj = $(".select_s input:checked").parents("tr");
        if (typeof(predefineFun) == 'undefined') {
          $obj.fadeOut();
        } else {
          $obj.each(function(i, n){
            var jobj = $(n);
            $.extend({ybo:predefineFun});
            $.ybo(jobj.attr("id"));
          });
        }
      $(".selectAll").attr("checked",false);
    } else {
      alert(prompt.errors);
    }
  });
}

/**
 * 批量转移分类
 * @param categoryId 分类id
 * @require 更新对应class="category"的分类td的内容
 * @TODO 与user_list中的审核功能合并抽取
 * @author gaojj@alltosun.com
 */
function moveCategory(categoryId)
{
  if(!confirm('确定要批量转移吗?')) return false;

  var id = getCheckedId();
    if (!id) {
        alert("你没有选择要操作的记录");
        return false;
    }

  var url = site_url + '/admin/category/move';
    var data = {'category_id': categoryId, 'id[]': id};
    $.getJSON(url, data, function(json){
        if (json.info != 'ok') {
            alert(json.info);
            return;
        }

        var categoryName = json.category_name;

        var articleCategorySelectors = [];

        $.each(id, function(k, v){
          // 更新对应class="category"的分类td的内容
            articleCategorySelectors.push('#list_'+v+' .category');
        });

        var newCategoryhtml = '<a href="admin/article&cat_id='+categoryId+'" target="_blank">'+categoryName+'</a>';
        var articleCategorySelector = articleCategorySelectors.join(',');

        $(articleCategorySelector).html(categoryName).effect("highlight", {}, 300).effect("highlight", {}, 300);
    });
}

/**
 * 获取页面中选中的checkbox对应的ids
 * @requires checkbox上统一加name="listSelect"
 * @requires tr的class="dataList1"
 * @return Array 所有选中的id数组
 */
function getCheckedIds()
{
  var ids = [];
  $("input.listSelect:checked").not(":disabled").each(function(){
    var selectId = $(this).closest("tr").attr("id").substring(8);
    ids.push(selectId);
  });
  return ids;
}

/**
 * 为了兼容原有后台程序移植过来的 将来将要被废除
 * 获取页面中选中的checkbox的值
 * 本方法中获取页面选中的checkbox必须在checkbox上统一加class="listCheck"，并且tr的class="list_1"
 * @return Array 所有选中的id数组
 * @author gaojj@alltosun.com
 */
function getCheckedId()
{
  var id = [];
  // checkbox上统一加class="listSelect"
    $("input.listSelect:checked").each(function(){
      // tr的class="list_1"
        var selectId = $(this).closest("tr").attr("id").substring(8);        
        id.push(selectId);
    });
    return id;
}

/**
 * 表格隔行换色
 * @return
 */
function interLineColor()
{
  $("tr:odd").removeClass("even").addClass("odd");
  $("tr:even").removeClass("odd").addClass("even");
}

/**
 * 是否是中文
 */
function isChinese(str)
{
  return new RegExp("[\\u4e00-\\u9fa5]", "").test(str);
}

// 获取排序的view_order
function getViewOrder()
{
  var viewOrderArr = { };
  var list = $(".dataBox tbody tr");
  var total = list.length;
  $.each(list ,function(viewOrder, v){
    var key = $(this).attr('id').substring(8);
    if (!key) {
      return true;
    }
    viewOrderArr[key] = viewOrder + 1;
  });
  return viewOrderArr;
}

// 判断一个对象是否是同一个对象 (只判断了第一层)
function isSameObj(obj1, obj2)
{
  for(var i in obj1) {
    if (obj1[i] !== obj2[i]) {
      return false;
    }
  }
  for(var j in obj2) {
    if (obj2[j] !== obj1[j]) {
      return false;
    }
  }
  return true;
}

// js添加商品
var Goods = (function(mod){
  mod.option = {
    getDataUrl : siteUrl + '/order/admin/get_goods.html',
    sltGoods   : 0,
    divTitle   : '添加订单商品'
  };

  mod.goodSelect = function (fn) {
    var html = mod.getGoods(0);
    if (!html) {
      return false;
    }
    ace.dialog({
      title: mod.option.divTitle,
      content:html,
      ok:function(){
        if (mod.option.sltGoods >= 1) {
          var tmp = fn();
          if (tmp != false) {
            qDialog.close()
          }
          return;
        }

        var goodsId = $('.js_goods option:selected').val();
        if (!goodsId || goodsId < 0) {
          showMsg('请选择要操作的商品');
          return false;
        }

        var skuInfo = mod.getGoods(goodsId, 'sku_info');
        var tmp = fn(skuInfo);
        if (tmp != false) {
          qDialog.close()
        }
      },
      cancel:function(){
        return true;
      }
    });

    $('.js_category').live('change', function(){
      var end = $(this).data('info');
      if (end == 'end') {
        return false;
      }
      var id = $(this).val();
      var html = mod.getGoods(id, '', 'number');
      $(this).parent().nextAll().remove()
      $(this).parent().after(html)
    });

    if (mod.option.sltGoods == 1) {
      $('.js_goodsIds').live('click', function(){
        var checked = $(this).attr('checked');
        var parent  = $(this).closest('.select-goods');
        if (checked != 'checked') {
          parent.find('.js_goodsSale').attr('style', 'display:none');
          parent.find('.goods-sale').html('');
        } else {
          var sale = parent.find('.js_goodsSale');
          var saleP = parseInt(sale.val());
          var price = $(this).parent().data('price');
          var discount = mod.discount(price, saleP);
          sale.parent().next().html(discount);
          sale.attr('style', '');
        }
      })
    }

    if (mod.option.sltGoods == 2) {
      $('.js_goodsIds').live('click', function(){
        var checked = $(this).attr('checked');
        var parent  = $(this).closest('.select-goods');
        if (checked != 'checked') {
          parent.find('.js_goodsSale').parent().attr('style', 'display:none');
          parent.find('.js_goodsSale').val('');
        } else {
          var sale = parent.find('.js_goodsSale');
          sale.parent().attr('style', '');
        }
      })
    }

    $('.js_goodsSale').live('keyup', function(){
      var num   = parseInt($(this).val());
      var price = $(this).data('price');
      var discount = mod.discount(price, num);
      $(this).parent().next().html(discount);
    });
  };

  mod.discount = function(price, num){
    var tmpNum = num;
    if (isNaN(tmpNum)) {
      tmpNum = 0;
    }
    if (tmpNum != 0) {
      tmpNum = Math.abs(tmpNum);
      var numLen = tmpNum.toString().length;
      var base   = '1';
      for (var i=0; i < numLen; i++) {
        base = base+'0';
      }
      var basic = parseInt(base);
      var discount = parseFloat(tmpNum / basic * parseFloat(price));
      return discount.toFixed(2);
    } else {
      return price.toFixed(2);
    }
  }
 
  mod.getGoods = function(pid, method, number){
    var tmp = '';
    $.ajax({
      type: "POST",
      url: mod.option.getDataUrl,
      data: { pid:pid, method:method, number:number },
      dataType: "json",
      async: false,
      cache: false,
      success: function(data){
       if (data.info != 'ok') {
         showMsg(data.info);
         return false;
       }
       tmp = data.data
      }
    });
    return tmp
  }
  return mod;
})(window.module || {});